"""
协调模式定义

定义多智能体系统中的各种协调模式和协调策略。
"""

from enum import Enum
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from datetime import datetime


class CoordinationMode(Enum):
    """协调模式"""
    HIERARCHICAL = "hierarchical"       # 层级协调
    COLLABORATIVE = "collaborative"     # 协作协调
    COMPETITIVE = "competitive"         # 竞争协调
    CONSENSUS = "consensus"             # 共识协调
    MARKET_BASED = "market_based"       # 市场化协调
    EMERGENCY = "emergency"             # 紧急协调
    SWARM = "swarm"                     # 群体协调
    HYBRID = "hybrid"                   # 混合协调


class CoordinationPattern(Enum):
    """协调模式"""
    
    # 数据处理协调模式
    DATA_PIPELINE = "data_pipeline"                 # 数据流水线
    DATA_AGGREGATION = "data_aggregation"           # 数据聚合
    DATA_VALIDATION = "data_validation"             # 数据验证
    
    # 研究协调模式
    RESEARCH_COLLABORATION = "research_collaboration"   # 研究协作
    PEER_REVIEW = "peer_review"                         # 同行评议
    KNOWLEDGE_SHARING = "knowledge_sharing"             # 知识共享
    
    # 决策协调模式
    DECISION_TREE = "decision_tree"                 # 决策树
    VOTING = "voting"                               # 投票决策
    CONSENSUS_BUILDING = "consensus_building"       # 共识构建
    ESCALATION = "escalation"                       # 升级决策
    
    # 交易协调模式
    ORDER_ROUTING = "order_routing"                 # 订单路由
    RISK_CONTROL = "risk_control"                   # 风险控制
    EXECUTION_OPTIMIZATION = "execution_optimization"   # 执行优化
    
    # 监控协调模式
    ALERT_PROPAGATION = "alert_propagation"         # 告警传播
    STATUS_REPORTING = "status_reporting"           # 状态报告
    PERFORMANCE_MONITORING = "performance_monitoring"   # 性能监控


@dataclass
class CoordinationRule:
    """协调规则"""
    id: str
    name: str
    description: str
    pattern: CoordinationPattern
    mode: CoordinationMode
    conditions: Dict[str, Any]
    actions: List[str]
    priority: int
    enabled: bool = True
    created_at: Optional[datetime] = None
    
    def __post_init__(self):
        if self.created_at is None:
            self.created_at = datetime.now()


@dataclass
class CoordinationContext:
    """协调上下文"""
    task_type: str
    participants: List[str]
    urgency_level: int
    complexity_score: float
    resource_constraints: Dict[str, Any]
    time_constraints: Optional[datetime]
    dependencies: List[str]
    metadata: Dict[str, Any]


class CoordinationStrategy:
    """协调策略基类"""
    
    def __init__(self, name: str, description: str):
        self.name = name
        self.description = description
        self.rules: List[CoordinationRule] = []
        self.metrics = {
            "success_rate": 0.0,
            "average_completion_time": 0.0,
            "resource_efficiency": 0.0,
            "conflict_resolution_rate": 0.0
        }
    
    def add_rule(self, rule: CoordinationRule):
        """添加协调规则"""
        self.rules.append(rule)
    
    def remove_rule(self, rule_id: str):
        """移除协调规则"""
        self.rules = [rule for rule in self.rules if rule.id != rule_id]
    
    def get_applicable_rules(self, context: CoordinationContext) -> List[CoordinationRule]:
        """获取适用的协调规则"""
        applicable_rules = []
        
        for rule in self.rules:
            if not rule.enabled:
                continue
            
            if self._evaluate_conditions(rule.conditions, context):
                applicable_rules.append(rule)
        
        # 按优先级排序
        applicable_rules.sort(key=lambda r: r.priority)
        return applicable_rules
    
    def _evaluate_conditions(self, conditions: Dict[str, Any], context: CoordinationContext) -> bool:
        """评估规则条件"""
        # 简化的条件评估逻辑
        for key, expected_value in conditions.items():
            if hasattr(context, key):
                actual_value = getattr(context, key)
                if actual_value != expected_value:
                    return False
        return True


class HierarchicalStrategy(CoordinationStrategy):
    """层级协调策略"""
    
    def __init__(self):
        super().__init__(
            name="层级协调",
            description="基于组织层级的自上而下协调策略"
        )
        self._initialize_rules()
    
    def _initialize_rules(self):
        """初始化层级协调规则"""
        # 战略决策规则
        strategic_rule = CoordinationRule(
            id="strategic_decision",
            name="战略决策协调",
            description="重大战略决策需要战略层参与",
            pattern=CoordinationPattern.ESCALATION,
            mode=CoordinationMode.HIERARCHICAL,
            conditions={"urgency_level": 5, "task_type": "strategic"},
            actions=["escalate_to_strategic", "notify_stakeholders"],
            priority=1
        )
        self.add_rule(strategic_rule)
        
        # 管理层协调规则
        management_rule = CoordinationRule(
            id="management_coordination",
            name="管理层协调",
            description="跨部门协调由管理层统筹",
            pattern=CoordinationPattern.DECISION_TREE,
            mode=CoordinationMode.HIERARCHICAL,
            conditions={"complexity_score": 0.7},
            actions=["assign_coordinator", "create_task_breakdown"],
            priority=2
        )
        self.add_rule(management_rule)


class CollaborativeStrategy(CoordinationStrategy):
    """协作协调策略"""
    
    def __init__(self):
        super().__init__(
            name="协作协调",
            description="基于平等协作的横向协调策略"
        )
        self._initialize_rules()
    
    def _initialize_rules(self):
        """初始化协作协调规则"""
        # 研究协作规则
        research_rule = CoordinationRule(
            id="research_collaboration",
            name="研究协作",
            description="研究任务采用协作模式",
            pattern=CoordinationPattern.RESEARCH_COLLABORATION,
            mode=CoordinationMode.COLLABORATIVE,
            conditions={"task_type": "research"},
            actions=["form_research_team", "share_resources", "peer_review"],
            priority=1
        )
        self.add_rule(research_rule)
        
        # 知识共享规则
        knowledge_rule = CoordinationRule(
            id="knowledge_sharing",
            name="知识共享",
            description="促进智能体间的知识共享",
            pattern=CoordinationPattern.KNOWLEDGE_SHARING,
            mode=CoordinationMode.COLLABORATIVE,
            conditions={},
            actions=["broadcast_insights", "update_knowledge_base"],
            priority=3
        )
        self.add_rule(knowledge_rule)


class ConsensusStrategy(CoordinationStrategy):
    """共识协调策略"""
    
    def __init__(self):
        super().__init__(
            name="共识协调",
            description="基于共识机制的协调策略"
        )
        self._initialize_rules()
    
    def _initialize_rules(self):
        """初始化共识协调规则"""
        # 投票决策规则
        voting_rule = CoordinationRule(
            id="voting_decision",
            name="投票决策",
            description="重要决策通过投票达成共识",
            pattern=CoordinationPattern.VOTING,
            mode=CoordinationMode.CONSENSUS,
            conditions={"urgency_level": 3},
            actions=["initiate_voting", "collect_votes", "announce_result"],
            priority=1
        )
        self.add_rule(voting_rule)


class EmergencyStrategy(CoordinationStrategy):
    """紧急协调策略"""
    
    def __init__(self):
        super().__init__(
            name="紧急协调",
            description="紧急情况下的快速响应协调策略"
        )
        self._initialize_rules()
    
    def _initialize_rules(self):
        """初始化紧急协调规则"""
        # 紧急响应规则
        emergency_rule = CoordinationRule(
            id="emergency_response",
            name="紧急响应",
            description="紧急情况下的快速协调",
            pattern=CoordinationPattern.ALERT_PROPAGATION,
            mode=CoordinationMode.EMERGENCY,
            conditions={"urgency_level": 5},
            actions=["immediate_alert", "bypass_normal_process", "direct_assignment"],
            priority=0
        )
        self.add_rule(emergency_rule)


class HybridStrategy(CoordinationStrategy):
    """混合协调策略"""
    
    def __init__(self):
        super().__init__(
            name="混合协调",
            description="结合多种协调模式的灵活策略"
        )
        self._initialize_rules()
    
    def _initialize_rules(self):
        """初始化混合协调规则"""
        # 自适应协调规则
        adaptive_rule = CoordinationRule(
            id="adaptive_coordination",
            name="自适应协调",
            description="根据情况动态选择协调方式",
            pattern=CoordinationPattern.DECISION_TREE,
            mode=CoordinationMode.HYBRID,
            conditions={"complexity_score": 0.6},
            actions=["analyze_context", "select_sub_strategy", "execute_hybrid"],
            priority=1
        )
        self.add_rule(adaptive_rule)
        
        # 多层次协调规则
        multilevel_rule = CoordinationRule(
            id="multilevel_coordination",
            name="多层次协调",
            description="同时使用层级和协作模式",
            pattern=CoordinationPattern.RESEARCH_COLLABORATION,
            mode=CoordinationMode.HYBRID,
            conditions={"task_type": "complex_research"},
            actions=["form_hierarchical_teams", "enable_cross_team_collaboration"],
            priority=2
        )
        self.add_rule(multilevel_rule)


# 预定义协调策略
COORDINATION_STRATEGIES = {
    CoordinationMode.HIERARCHICAL: HierarchicalStrategy(),
    CoordinationMode.COLLABORATIVE: CollaborativeStrategy(),
    CoordinationMode.CONSENSUS: ConsensusStrategy(),
    CoordinationMode.EMERGENCY: EmergencyStrategy(),
    CoordinationMode.HYBRID: HybridStrategy(),
}


def get_coordination_strategy(mode: CoordinationMode) -> Optional[CoordinationStrategy]:
    """获取协调策略"""
    return COORDINATION_STRATEGIES.get(mode)


def select_coordination_mode(context: CoordinationContext) -> CoordinationMode:
    """选择协调模式"""
    # 紧急情况
    if context.urgency_level >= 5:
        return CoordinationMode.EMERGENCY
    
    # 高复杂度任务
    if context.complexity_score >= 0.8:
        return CoordinationMode.HIERARCHICAL
    
    # 研究类任务
    if context.task_type in ["research", "analysis"]:
        return CoordinationMode.COLLABORATIVE
    
    # 需要多方同意的决策
    if context.task_type in ["decision", "policy"]:
        return CoordinationMode.CONSENSUS
    
    # 默认协作模式
    return CoordinationMode.COLLABORATIVE